package org.bioversityinternational.mgbms.model.dao;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.bioversityinternational.mgbms.model.dao.base.BaseDao;
import org.bioversityinternational.mgbms.model.domain.Centre;
import org.bioversityinternational.mgbms.model.domain.ContactCentre;

@Component
public class CentreDao extends BaseDao<Centre, Integer>
{
	private static final Logger LOG = Logger.getLogger(CentreDao.class);
	
	public CentreDao() {
		super(Centre.class);		
        LOG.debug("CentreDao constructed");
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.SUPPORTS)
	public HashMap<Integer, String> listValidCentres() {
		String sQuery = "select id,acronym from " + type.getName() + " where name is not null and length(name) > 0 and acronym is not null and length(acronym) > 0 order by acronym";
		Query query = getSession().createQuery(sQuery);
		
		HashMap<Integer, String> result = new LinkedHashMap<Integer, String>();
		List<Object[]> records = query.list();
		for (Object[] record : records)
			result.put((Integer) record[0], (String) record[1] );
		
        LOG.debug("hql: " + sQuery + " -> " + result.size() + " results");
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.SUPPORTS)
	public ContactCentre getLatestCentreForContact(Integer contactId) {
		String sQuery = "from " + ContactCentre.class.getName() + " where contact.id=:P order by startDate desc";
		Query query = getSession().createQuery(sQuery);
		query.setParameter("P", contactId);
		query.setMaxResults(1);
		
		ContactCentre contactCentre = (ContactCentre) query.uniqueResult();
		
        LOG.debug("hql: " + sQuery + " -> " + (contactCentre == null ? 0 : 1) + " result");
		return contactCentre;
	}

	@Override
	public Integer getIdFromString(String sIdAsString) {
		return Integer.parseInt(sIdAsString);
	}
		
}

